package helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class LogfileWriter {
	public Context c;

	private String filename = "";
	private String filepath = "intellifit_logs";
	// File myInternalFile;
	File myExternalFile;
	File myExternalGyroFile;
	public static String static_nextNumberStr;

	public LogfileWriter() {

		// get max file number
		File f = new File(Environment.getExternalStorageDirectory()
				+ File.separator + filepath);
		File[] files = f.listFiles();
		int actNumber, maxNumber = 0;

		for (int i = 0; i < files.length; i++) {
			try {
				actNumber = Integer.valueOf(files[i].getName().split("_")[0]);
			} catch (Exception e) {
				actNumber = 0;
			}

			if (actNumber > maxNumber) {
				maxNumber = actNumber;
			}
		}

		String nextNumberStr = String.valueOf(maxNumber + 1);
		switch (nextNumberStr.length()) {
		case 1:
			nextNumberStr = "000" + nextNumberStr;
			break;
		case 2:
			nextNumberStr = "00" + nextNumberStr;
			break;
		case 3:
			nextNumberStr = "0" + nextNumberStr;
			break;
		default:
		}

		// Log.i("FILES: ", String.valueOf(maxNumber));//maxNumber);

		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		filename = "ifLog_" + dateFormat.format(date);
		filename = filename.replace('/', '_');
		filename = filename.replace(':', '-');
		filename = nextNumberStr + '_' + filename;

		static_nextNumberStr = nextNumberStr;
	}

	public void setContext(Context c) {
		this.c = c;
		ContextWrapper contextWrapper = new ContextWrapper(this.c);
		File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
		// myInternalFile = new File(directory, filename);

		// init external
		// check if external storage is available and not read only
		if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
			Log.e("intellifit_error", "CANNOT WRITE TO EXTERNAL MEM");
		} else {

			File dir = new File(Environment.getExternalStorageDirectory()
					+ File.separator + filepath);
			if (!dir.exists())
				dir.mkdirs();
			try {
				myExternalFile = new File(dir.getAbsolutePath() + "/"
						+ filename + ".csv");
				if (!myExternalFile.exists()) {
					myExternalFile.createNewFile();
					// send out broadcast, so that the file is immeadiatley
					// availible using the explorer
					c.sendBroadcast(new Intent(
							Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
									.fromFile(myExternalFile)));
				}

			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private static boolean isExternalStorageReadOnly() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	private static boolean isExternalStorageAvailable() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	public void saveToExternalStorage(String s, String destination) {

		File theFile;
		if (destination == "g") {
			theFile = myExternalGyroFile;
		} else {
			theFile = myExternalFile;
		}

		try {
			FileOutputStream fos = new FileOutputStream(theFile, true);
			OutputStreamWriter os = new OutputStreamWriter(fos);
			os.write(s + "\n");
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}